public class Test1 {
    public int LastRemaining_Solution (int n, int m) {
        // write code here
        int[] arr = new int[n];
        int index = 0;
        for (int i = 0; i < n-1; i++) {
            int count = 0;
            while (count < m) {
                if (arr[index%n] == 0) {
                    count++;
                }
                index++;
            }
            arr[(index-1) % n] = 1;
        }
        for (int i = 0; i < n; i++) {
            if (arr[i] == 0) {
                return i;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        Test1 test1 = new Test1();
        System.out.println(test1.LastRemaining_Solution(5, 3));
    }
}
